<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="150px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="设备图片" prop="picUrl">
            <UploadImg
              v-model="formData.picUrl"
              @change="handleImageChange"
              :deviceId="formData.id ?? '0'"
              :picUrl="formData.picUrl ? formData.picUrl : ''"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="设备分组" prop="groupId">
            <el-tree-select
              v-model="formData.groupId"
              :data="dataList"
              :props="defaultProps"
              check-strictly
              node-key="id"
              placeholder="请选择分组"
              class="!w-240px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备服务器" prop="mqttConfigId">
            <el-select v-model="formData.mqttConfigId" placeholder="请选择设备服务器">
              <el-option
                v-for="item in mqttConfigList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                class="!w-240px"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="设备类型" prop="deviceType">
            <el-select
              v-model="formData.deviceType"
              placeholder="请选择设备类型"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.MQTT_DEVICE_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="网关SN编号" prop="gatewayId">
            <el-input v-model="formData.gatewayId" placeholder="网关SN编号" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="formData.deviceName" placeholder="设备名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="上送名称" prop="cxName">
            <el-input v-model="formData.cxName" placeholder="上送名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="报警状态" prop="alarmStatus">
            <el-radio-group v-model="formData.alarmStatus">
              <el-radio
                v-for="dict in getStrDictOptions(DICT_TYPE.MQTT_CONFIG_ENABLED)"
                :key="dict.value"
                :label="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="默认报警" prop="alarmDefult">
            <el-radio-group v-model="formData.alarmDefult">
              <el-radio
                v-for="dict in getStrDictOptions(DICT_TYPE.MQTT_CONFIG_ENABLED)"
                :key="dict.value"
                :label="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="设备的固件编号" prop="firmwareId">
            <el-input v-model="formData.firmwareId" placeholder="请输入设备的固件编号" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="设备唯一标识符" prop="deviceKey">
            <el-input
              v-model="formData.deviceKey"
              placeholder="唯一标识符"
              :disabled="formData.deviceKey != null"
            >
              <template #suffix>
                <el-button
                  icon="Refresh"
                  :disabled="formData.deviceKey != null"
                  @click="generateDeviceKey"
                  type="primary"
                  size="small"
                  style="margin-right: -12px"
                  >生成</el-button
                >
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="联网方式" prop="networkType">
            <el-select
              v-model="formData.networkType"
              placeholder="请选择联网方式"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.MQTT_DEVICE_NETWORKTYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备编号" prop="serialNumber">
            <el-input v-model="formData.serialNumber" placeholder="请输入设备序列号" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="设备所在地" prop="address">
            <el-input v-model="formData.address" placeholder="设备所在地" readonly>
              <template #suffix>
                <el-button
                  icon="el-icon-location"
                  @click="openMapDialog"
                  type="primary"
                  style="margin-right: -12px"
                  >地图</el-button
                >
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="经度" prop="longitude">
            <el-input v-model="formData.longitude" placeholder="经度" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纬度" prop="latitude">
            <el-input v-model="formData.latitude" placeholder="纬度" readonly />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- <el-form-item label="角色">
        <el-select v-model="formData.roleIds" multiple placeholder="请选择角色">
          <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item> -->

      <el-form-item label="备注" prop="nickname">
        <el-input v-model="formData.nickname" placeholder="备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>

    <el-dialog v-model="mapDialogVisible" title="选择位置" width="60%" @opened="onMapDialogOpened">
      <TencentMapSelector
        ref="mapSelectorRef"
        @location-selected="onLocationSelected"
        :address="formData.address"
        :longitude="formData.longitude"
        :latitude="formData.latitude"
      />
    </el-dialog>
  </Dialog>
</template>

<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { DeviceApi, DeviceVO } from '@/api/mqtt/device'
import UploadImg from './upload.vue'
import type { UploadFile } from 'element-plus'
import { ConfigApi } from '@/api/mqtt/config'
import { DeviceGroupApi } from '@/api/mqtt/devicegroup'
import TencentMapSelector from './TencentMapSelector.vue'
import { defaultProps, handleTree } from '@/utils/tree'
import * as RoleApi from '@/api/system/role'
const roleList = ref([] as RoleApi.RoleVO[]) // 角色的列表

const mapDialogVisible = ref(false)
const mapSelectorRef = ref()
const openMapDialog = () => {
  // alert(mqttConfigStore.getValue('weixin_map'))
  mapDialogVisible.value = true
}
const onMapDialogOpened = () => {
  mapSelectorRef.value?.initMap?.()
  // 新增：有地址时自动定位
  if (formData.value.address) {
    mapSelectorRef.value?.locateByAddress?.(formData.value.address)
  }
}
const onLocationSelected = ({ address, longitude, latitude }) => {
  formData.value.address = address
  formData.value.longitude = longitude
  formData.value.latitude = latitude
  mapDialogVisible.value = false
}
/** IoT 设备 表单 */
defineOptions({ name: 'DeviceForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref<Partial<DeviceVO>>({
  id: undefined,
  deviceKey: undefined,
  mqttConfigId: undefined,
  alarmStatus: '1',
  alarmDefult: '0',
  deviceName: undefined,
  cxName: undefined,
  nickname: undefined,
  networkType: undefined,
  serialNumber: undefined,
  picUrl: undefined,
  groupId: undefined,
  productId: undefined,
  productKey: undefined,
  deviceType: undefined,
  gatewayId: undefined,
  state: undefined,
  onlineTime: undefined,
  offlineTime: undefined,
  activeTime: undefined,
  ip: undefined,
  firmwareId: undefined,
  deviceSecret: undefined,
  mqttClientId: undefined,
  mqttUsername: undefined,
  mqttPassword: undefined,
  authType: undefined,
  latitude: undefined,
  longitude: undefined,
  areaId: undefined,
  address: undefined,
  config: undefined
})

const formRules = reactive({
  networkType: [{ required: true, message: '请选择联网方式', trigger: 'change' }],
  picUrl: [{ required: true, message: '请上传设备图片', trigger: 'change' }],
  alarmStatus: [{ required: true, message: '请选择报警状态', trigger: 'change' }],
  alarmDefult: [{ required: true, message: '请选择默认报警', trigger: 'change' }],
  groupId: [{ required: true, message: '请选择设备分组', trigger: 'change' }],
  mqttConfigId: [{ required: true, message: '请选择设备服务器', trigger: 'change' }],
  deviceType: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
  deviceKey: [{ required: true, message: '设备唯一标识符不能为空', trigger: 'blur' }],
  deviceName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
  address: [{ required: true, message: '请选择设备地址', trigger: 'blur' }],
  state: [{ required: true, message: '设备状态', trigger: 'blur' }],
  gatewayId: [{ required: true, message: '网关SN编号不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const uploadRef = ref() // 上传组件 Ref
const mqttConfigList = ref<any[]>([]) // mqtt配置列表
const groupList = ref<any[]>([]) // 设备分组列表
// 存储上传的文件对象
const uploadedFile = ref<UploadFile | null>(null)

// 处理图片变化
const handleImageChange = (file: UploadFile | null) => {
  console.log('图片变化:', file)
  uploadedFile.value = file
}
const dataList = ref<Tree[]>([]) // 树形结构
/** 打开弹窗 */
const open = async (type: string, id?: number, initData?: any) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  // 获取mqtt配置信息
  await ConfigApi.getConfigPage({ page: 1, size: 100 }).then((res) => {
    mqttConfigList.value = res.list
  })

  // 获取设备分组信息
  const res = await DeviceGroupApi.getSimpleGroupList(null)
  dataList.value = []
  dataList.value.push(...handleTree(res))
  // 重置表单
  resetForm()

  const roleList = ref([] as RoleApi.RoleVO[]) // 角色的列表

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DeviceApi.getDevice(id)
      // 如果有额外初始数据，赋值（如address/longitude/latitude）
      if (initData) {
        formData.value.address = initData.address
        formData.value.longitude = initData.longitude
        formData.value.latitude = initData.latitude
      }
    } finally {
      formLoading.value = false
    }
  } else if (initData) {
    formData.value.address = initData.address
    formData.value.longitude = initData.longitude
    formData.value.latitude = initData.latitude
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()

  // 处理图片上传（如果有文件需要上传到服务器）
  if (uploadedFile.value && uploadedFile.value.raw) {
    try {
      // 临时使用本地URL（实际项目中应该上传到服务器）
      formData.value.picUrl = uploadedFile.value.url || undefined
    } catch (error) {
      console.error('图片上传失败:', error)
      message.error('图片上传失败，请重试')
      return
    }
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as DeviceVO
    if (formType.value === 'create') {
      await DeviceApi.createDevice(data)
      message.success(t('common.createSuccess'))
    } else {
      await DeviceApi.updateDevice(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    deviceKey: undefined,
    mqttConfigId: undefined,
    deviceName: undefined,
    nickname: undefined,
    serialNumber: undefined,
    picUrl: undefined,
    groupId: undefined,
    productId: undefined,
    productKey: undefined,
    deviceType: undefined,
    gatewayId: undefined,
    state: undefined,
    onlineTime: undefined,
    offlineTime: undefined,
    activeTime: undefined,
    ip: undefined,
    firmwareId: undefined,
    deviceSecret: undefined,
    mqttClientId: undefined,
    mqttUsername: undefined,
    mqttPassword: undefined,
    authType: undefined,
    latitude: undefined,
    longitude: undefined,
    areaId: undefined,
    address: undefined,
    config: undefined
  }
  formRef.value?.resetFields()

  // 清空上传的文件
  uploadedFile.value = null
  // 清空上传组件
  uploadRef.value?.clearFile()
}

/** 生成设备唯一标识符 */
const generateDeviceKey = () => {
  // 生成12位UUID
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let uuid = ''
  for (let i = 0; i < 12; i++) {
    uuid += chars[Math.floor(Math.random() * chars.length)]
  }
  formData.value.deviceKey = uuid
  // message.success('设备唯一标识符生成成功')
}
</script>
